<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/tree/list' }">商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.kw"
          placeholder="输入商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
            size="small"
            type="success"
            icon="el-icon-plus"
            @click="handleEdit()"
        >添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表 hotelId roomNo location floor price status-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" label="图片" width="80">
        <template slot-scope="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.pic"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="category" label="类别" width="130">
        <template slot-scope="scope">
          <el-tag size="small" type="primary">{{ scope.row.categoryInfo.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="商品名称" show-overflow-tooltip>
      </el-table-column>
      <!-- <el-table-column align="center" prop="merchant.nickName" label="善书者" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="mname">{{ scope.row.merchant.nickName }}</span>
        </template>
      </el-table-column> -->
      <el-table-column align="center" prop="quantity" label="库存" width="80">
      </el-table-column>
      <el-table-column align="center" label="价格" width="100">
        <template slot-scope="scope">
          ￥<strong style="color: #F56C6C;">{{ scope.row.price|amountString }}</strong>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="saleCount" label="累计销量" width="100">
      </el-table-column>
      <el-table-column align="center" prop="subTitle" label="简述" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1" style="color:#67C23A;">正常</span>
          <span v-else-if="scope.row.status == -1" style="color:#666666;">已下架</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleDetail(scope.$index, scope.row)" icon="el-icon-document">详情</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.$index, scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" @click="offShelf(scope.$index, scope.row, -1)" v-if="scope.row.status == 1"  icon="el-icon-download">下架</el-button>
          <el-button size="mini" type="success" @click="offShelf(scope.$index, scope.row, 1)" v-if="scope.row.status == -1" icon="el-icon-upload2">上架</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="60%"
      :close-on-click-modal=false
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="商品类别" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择" size="small" @change="changeCategory($event)">
            <el-option
              v-for="item in allCategory"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="subTitle">
          <el-input
            size="small"
            v-model="editForm.subTitle"
            placeholder="显示在商品称下方，简要介绍商品"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input
            size="small"
            v-model="editForm.quantity"
            auto-complete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price" v-if="editForm.category!=21">
          <el-input
            size="small"
            v-model="editForm.price"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price" v-else>
          <el-input
            size="small"
            disabled
            v-model="editForm.price"
          ></el-input>
          <p class="ptip">个性定制商品单价固定为1元，与客户协调好价格后拍多件即可，请保证数量充足。</p>
        </el-form-item>
        <el-form-item label="商品详情" prop="describ" id='quillEditorQiniu'>
          <!-- 基于elementUi的上传组件 el-upload-->
          <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :accept="'image/*'"
              :show-file-list="false"
              :on-success="uploadEditorSuccess"
              :on-error="uploadEditorError"
              :before-upload="beforeEditorUpload">
          </el-upload>
          <quill-editor  class="editor"  v-model="editForm.describ" ref="customQuillEditor" :options="editorOption" >
          </quill-editor>
        </el-form-item>
        <el-form-item label="展示图片" prop="role">
          <el-upload 
            class="avatar-uploader showUploader"
            action
            :auto-upload="false"
            :show-file-list="false"
            :on-remove="handleRemoveLogo"
            :on-change="uploadLogoFile"
          >
            <ul class="img-list">
              <li v-if="editForm.pic==''" class="el-icon-plus avatar-uploader-icon"></li>
            </ul>
          </el-upload>
          <ul class="img-list" v-if="editForm.pic!=''">
            <li class="img-li" style="width: 180px;">
              <img :src="editForm.pic" class="avatar" style="width: 180px;height: 160px;"/>
              <i class="logo-remove el-icon-delete" @click="handleRemoveLogo()"></i>
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          v-loading.fullscreen.lock="fullscreenLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!--详情对话框-->
    <el-dialog
      title="商品信息详情"
      :visible.sync="roomDescVisible"
      width="60%"
      :close-on-click-modal=false
      @click="closeDialog2"
    >
    <el-descriptions class="margin-top" :column="2" border>
      <el-descriptions-item label="类型">
        <el-tag size="small" effect="dark" v-if="currDetailData.categoryInfo!=null">{{ currDetailData.categoryInfo.name }}</el-tag>
      </el-descriptions-item>
        <el-descriptions-item label="商品名称" labelStyle="width: 160px;">{{ currDetailData.name }}</el-descriptions-item>
        <el-descriptions-item label="简要描述" labelStyle="width: 160px;" span="2">{{ currDetailData.subTitle }}</el-descriptions-item>
        <el-descriptions-item label="状态" labelStyle="width: 160px;">
          <span v-if="currDetailData.status == 1" style="color:#67C23A;">正常</span>
          <span v-else-if="currDetailData.status == -1" style="color:#666666;">已下架</span>
        </el-descriptions-item>
        <el-descriptions-item label="库存" labelStyle="width: 160px;">{{ currDetailData.quantity }}</el-descriptions-item>
        <el-descriptions-item label="价格" labelStyle="width: 160px;">{{ currDetailData.price|amountString }}</el-descriptions-item>
        <el-descriptions-item label="累计销量" labelStyle="width: 160px;">{{ currDetailData.saleCount }}</el-descriptions-item>
    </el-descriptions>
    <div v-html="currDetailData.describ" class="introduction"></div>
    <div class="demo-image">
      <div class="block" v-for="fit in currDetailPics" :key="fit">
        <a :href="fit" target="_blank">
        <el-image
          style="width: 100px; height: 100px"
          :src="fit"
          fit="cover"></el-image>
        </a>
      </div>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination.vue";
import { fileUploader } from '@/api/upload.js'
import * as Quill from 'quill'
import { MerchantProductList, MerchantSaveProduct, UpdateProductStatus, GetAvCategory } from '@/api/api.js'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons

  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],
  ['link', 'image'],
  ['clean']                                         // remove formatting button
];


export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      roomDescVisible: false, //详情对话框显示与隐藏
      title: "添加商品",
      editForm: {
        productId: '',
        name: '',
        subTitle: '',
        category: '',
        status: 1,
        price: '',
        quantity: '',
        pic: '',
        describ: '',
        status: 1,
        viewCount: 0,
        saleCount: 0,
      },
      allCategory: [],
      saveOrUpdate: 1,
      files: {},
      // rules表单验证
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        category: [{ required: true, message: "请选择类型", trigger: "blur" }],
        quantity: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
        period: [{ required: true, message: "请输入成熟周期", trigger: "blur" }],
      },
      formInline: {
        page: 1,
        limit: 10,
        kw: "",
        currentPage: 1,
        pageSize: 10,
      },
      listData: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
      currDetailData: {},
      currDetailPics: [],
      selectedOptions: [],
      fullscreenLoading: false,
      uploadImgUrl:"/api/admin/uploadPic",
      uploadUrlPath:"没有文件上传",
      quillUpdateImg:false,
      editorOption:{
        placeholder:'请输入正文',
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('#quillEditorQiniu .avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              },
            }
          }
        }
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
    //读取所有分类
    GetAvCategory({})
      .then(res => {
        this.loading = false
        if (res.success) {
          this.allCategory = res.data
        }
      })
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取商品列表
    getdata(parameter) {
      this.loading = true;
      MerchantProductList(parameter)
        .then((res) => {
          this.loading = false;
          if (res.success) {
            this.listData = res.data.records;
            this.pageparm.currentPage = res.data.currentPage;
            this.pageparm.pageSize = res.data.pageSize;
            this.pageparm.total = res.data.totalrecord;
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {
          this.editFormVisible = false;
          this.loading = false;
          this.$message.error("获取数据失败，请稍后再试！");
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.currentPage = parm.currentPage;
      this.formInline.pageSize = parm.pageSize;
      this.formInline.total = parm.total
      this.getdata(this.formInline);
    },
    // 搜索事件
    search() {
      console.log('搜索：', this.formInline)
      this.getdata(this.formInline)
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.title = "修改信息";
        this.saveOrUpdate=2
        this.editForm.productId=row.productId
        this.editForm.name=row.name
        this.editForm.category=row.category
        this.editForm.status=row.status
        this.editForm.price=row.price
        this.editForm.saleCount=row.saleCount
        this.editForm.viewCount=row.viewCount
        this.editForm.pic=row.pic
        this.editForm.describ=row.describ
      } else {
        this.title = "添加";
        this.editForm.name=''
        this.editForm.category=''
        this.editForm.status=1
        this.editForm.price=''
        this.editForm.quantity=''
        this.editForm.pic=''
        this.editForm.saleCount=0
        this.editForm.viewCount=0
        this.editForm.describ=''
        this.editForm.subTitle=''
      }
    },
    
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          this.fullscreenLoading = true
          MerchantSaveProduct(this.editForm)
            .then((res) => {
              this.fullscreenLoading = false
              this.editFormVisible = false
              this.loading = false
              if (res.success) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "保存成功！",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 改变状态
    offShelf(index, row, status) {
      let msg = "确定要下架该商品吗？"
      if(status == 1){
        msg = "确定要重新上架该商品吗？"
      }
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.fullscreenLoading = true
        UpdateProductStatus({productId: row.productId, status: status})
          .then((res) => {
            this.fullscreenLoading = false
            if (res.success) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.getdata(this.formInline);
            } else {
              this.$message({
                type: "info",
                message: res.msg,
              });
            }
          }).catch((err) => {
            this.fullscreenLoading = false
            this.loading = false;
            this.$message.error("操作失败，请稍后再试！");
          });
      })
    },
    //显示编辑界面
    handleDetail: function (index, row) {
      this.roomDescVisible = true
      this.currDetailData = row
      // this.currDetailPics = row.pics.split(",")
    },

    changeCategory(e){
      console.log('选择类型：',e)
      if(e==21){
        this.editForm.price=1
      }
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
    },
    closeDialog2() {
      this.roomDescVisible = false;
    },
    // 删除图片
    handleRemoveLogo(file){
      this.editForm.pic=''
      console.log('移除商品主图！',this.editForm.pic)
    },
    
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 上传图片
    uploadLogoFile(file){
      const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
      const isJPG = typeArr.indexOf(file.raw.type) !== -1;
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("只能是图片!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        this.$refs.upload.clearFiles();
        this.files = null;
        return;
      }
      var formData = new FormData();
      formData.append("file", file.raw)
      fileUploader(formData).then((res) => {
        console.log('展示图上传成功', res.data)
        if (res.data.success) {
          this.editForm.pic=res.data.data
          // console.log('加入LOGO',this.editForm)
        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    // 富文本编辑器：上传图片成功
    uploadEditorSuccess(res, file) {
      console.log("上传成功")
      // this.$emit('upload',res, file)
      console.log(res, file);
      //拼接出上传的图片在服务器的完整地址
      let imgUrl=res.data;
      let type=imgUrl.substring(imgUrl.lastIndexOf(".")+1);
      console.log(type);
      // 获取富文本组件实例
      let quill = this.$refs.customQuillEditor.quill;
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片 res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', imgUrl)
      // 调整光标到最后
      quill.setSelection(length + 1)
      //取消上传动画
      this.quillUpdateImg = false;
    },
    // 上传(文件)图片失败
    uploadEditorError(res, file) {
      console.log(res);
      console.log(file);
      //页面提示
      this.$message.error('上传图片失败')
      //取消上传动画
      this.quillUpdateImg = false;
    },
    //上传图片之前async
    beforeEditorUpload(res, file){
      //显示上传动画
      this.quillUpdateImg = true;
      console.log(res);
    },
    //上传组件返回的结果
    uploadResult:function (res){
      this.uploadUrlPath=res;
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.user-search .el-form--inline .el-form-item{
  vertical-align: baseline;
}
.user-search .el-form-item{
  margin-bottom: 10px;
}
.avatar-uploader /deep/ .el-upload {
    border-radius: 6px;
    background-color: #fff;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #41a8a8;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    border: 1px dashed #8c939d;
    width: 180px;
    height: 140px;
    line-height: 140px;
    text-align: center;
  }
  .showUploader /deep/ .el-upload-list{
    display: none;
  }
  .avatar {
    width: 100%;
    height: 140px;
    display: block;
  }
  .img-list{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
  }
  .img-list .img-li{
    display: inline-block;
    margin-right: 1%;
    width: 32%;
    margin-bottom: 5px;
  }
  .quill-editor {
    height: 250px;
    margin-bottom: 100px;
  }
  .introduction, .demo-image{
    width: 80%;
    margin: 15px auto;
  }
  .el-image{
    cursor: zoom-in;
  }
  .mname{
    color: #0075b6;
    font-weight: bold;
  }
  .block{
    display: inline-block;
    width: 100px;
    margin: 10px;
  }
  .logo-remove{
    cursor: pointer;
  }
</style>

 
 